package com.cr.crsystem.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cr.crsystem.common.utils.Result;
import com.cr.crsystem.system.entity.User;
import com.cr.crsystem.system.model.LoginModel;
import com.cr.crsystem.system.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author su
 * @Date 2022/6/21 13:45
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/system")
@Api(tags = "用户登录")
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<User> login(@RequestBody LoginModel loginModel) {
        Result<User> result = new Result<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginModel.getUsername());
        User user = userService.getOne(queryWrapper);
        result = (Result<User>) userService.checkUserIsEffective(user,loginModel);
        if (!result.isSuccess()) {
            return result;
        }
        result.setResult(user);
        result.success("登录成功");
        return result;
    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Result<?> logout(@RequestBody User user) {
        try {
            String name = user.getUsername();
            User sysUser = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, name));
            if (sysUser != null) {
                log.info(" 用户名:  " + sysUser.getRealName() + ",退出成功！ ");
                return Result.OK().success("退出登录成功！");
            } else {
                return Result.error("退出登录失败!");
            }
        } catch (ExpiredJwtException e) {
            log.error(e.getMessage(), e);
            return Result.OK().success("请重新登录!");
        }

    }

}
